/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 

package com.nokia.example.wordpress.networking;

import java.util.Vector;

/**
 * Opeation for retrieving blogs from the server.
 */
public class GetUsersBlogsOperation extends NetworkOperation {

    /**
     * Listener interface for reporting the results.
     */
    public interface Listener {

        /**
         * Returns the retrieved blogs. In case of an error, a null is returned
         * and an error message is set in Blog.faultString.
         * @param blogs Retrieved blogs or null in case of an error.
         */
        public void blogsReceived(Vector blogs);
    }
    private static final String WP_GET_USERS_BLOGS = "wp.getUsersBlogs";
    private String blogUrl;
    private String blogUser;
    private String blogUserPassword;
    private Listener listener;

    /**
     * Creates the operation.
     * @param listener
     * @param blogUrl URL to send the request to
     * @param blogUser Username
     * @param blogUserPassword Password for the user
     */
    public GetUsersBlogsOperation(Listener listener,
            String blogUrl, String blogUser, String blogUserPassword) {
        this.blogUrl = blogUrl;
        this.blogUser = blogUser;
        this.blogUserPassword = blogUserPassword;
        this.listener = listener;
    }

    /**
     * Starts the operation.
     */
    public void start() {
        Request req = new Request(WP_GET_USERS_BLOGS);
        req.addStringParam(blogUser);
        req.addStringParam(blogUserPassword);
        Network nw = new Network(this);
        nw.startHttpPost(blogUrl, req.request());
    }

    /**
     * Parses the server response and calls the listener.
     * @param response
     */
    public void networkHttpPostResponse(String response) {
        try {
            UsersBlogsParser handler = new UsersBlogsParser();
            parse(response, handler);

            // Store some additional info for convenience.
            for (int i = 0; i < handler.blogs.size(); i++) {
                Blog blog = (Blog) handler.blogs.elementAt(i);
                blog.blogUser = blogUser;
                blog.blogUserPassword = blogUserPassword;
            }

            listener.blogsReceived(handler.blogs);
        } catch (ParseError e) {
            listener.blogsReceived(null);
        }
    }
}


